<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Model\AccessToken;
use App\Model\City;
use Carbon\Carbon;
use GuzzleHttp\Client;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Validation\Contract\ValidatorFactoryInterface;

#[\Hyperf\HttpServer\Annotation\Controller]
class TestController
{
    #[Inject]
    protected ValidatorFactoryInterface $validationFactory;

    #[Inject]
    protected RequestInterface $request;

    public function __construct()
    {
        $this->config = [
            'appid' => 'wx7fc1ef73941f5f9f',//小程序 appId
            'secret' => '77fb98a158198338306c813b74d01e20'//小程序 appSecret
        ];
    }

    public function getAccessToken()
    {
        $accessToken = AccessToken::active();
        if ($accessToken && $accessToken->access_token) {
            return $accessToken->access_token;
        }

        $config = $this->config;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?appid=' . ($config['appid'] ?? '') . '&secret=' . ($config['secret'] ?? '') . '&grant_type=client_credential';
//        $option = [
//            'appid' => $config['appid'] ?? '',
//            'secret' => $config['secret'] ?? '',
//            'grant_type' => 'client_credential',//固定参数
//        ];
        $client = new Client(['verify' => false]);
        $result = $client->request('get', $url);
        $result = json_decode($result->getBody()->getContents(), true);
        if (!($result['access_token'] ?? '')) {
            return '';
        }

        $accessToken = new AccessToken();
        $accessToken->access_token = $result['access_token'];
        $accessToken->expiration_time = Carbon::parse(date('Y-m-d H:i:s'))->addSeconds(7000);
        $accessToken->save();
        return $result['access_token'] ?? '';
    }

    #[RequestMapping(path: "", methods: "get")]
    public function index()
    {
        //$jsCode:前端登录时获取的 code，可通过wx.login获取
        $config = $this->config;
        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . ($config['appid'] ?? '') . '&secret=' . ($config['secret'] ?? '') . '&grant_type=authorization_code&js_code=' . $jsCode;
        $client = new Client(['verify' => false]);
        $result = $client->request('get', $url);
        $result = json_decode($result->getBody()->getContents(), true);

        return [
            'result'
        ];
        return $result['openid'] ?? '';
        return 'test was closed';
    }
}
